//
//  AddPictureViewController.m
//  gpos_app
//
//  Created by 崔航飞 on 2018/8/20.
//  Copyright © 2018年 apple. All rights reserved.
//

#import "AddPictureViewController.h"
#import "Masonry.h"
#import "MyCusCollectionViewCell.h"
#import "LHGroupViewController.h"
#import "LHCollectionViewController.h"
#import "LHConst.h"
#import "UIImageView+WebCache.h"
@interface AddPictureViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,MyCusCollectionViewCellDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate,UIGestureRecognizerDelegate>
{
    UICollectionView *mainCollectionView;
}
@property (nonatomic,strong)UIImageView *BottomView;
@property (nonatomic,strong) UIView *backgroundViews;

@property (nonatomic,strong) UILabel *merchantlab;
@property (nonatomic,strong) NSMutableArray *imageArray;//存放处理完的图片
@property (nonatomic,strong) UIScrollView *scrolView;//滚动视图
@property (nonatomic,strong) NSMutableArray *scrollSubViews;//存放图片子视图
@property (nonatomic,strong) NSMutableArray *scrollSubFrame;//子视图的frame
@property (nonatomic,strong) NSMutableArray *localLength;//每张图片的尺寸

@end

@implementation AddPictureViewController
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden=NO;
    //去掉返回的文字
    self.navigationController.navigationBar.topItem.title = @"";
    self.navigationItem.title=@"添加图片";
    
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
        

}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    
}
-(void)viewDidLayoutSubviews{
    
    [super viewDidLayoutSubviews];
    self.tabBarController.tabBar.hidden = YES;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor whiteColor];
    self.navigationController.navigationBar.backgroundColor=[UIColor whiteColor];
    self.navigationController.navigationBar.tintColor=[UIColor blackColor];
    self.imageArray = [NSMutableArray new];
    self.scrollSubViews = [NSMutableArray new];
    self.scrollSubFrame = [NSMutableArray new];
    self.localLength = [NSMutableArray new];

    [self initUI];
}
-(void)initUI{
    if (self.arrs.count !=0) {
        self.imageArray=self.arrs;
    }
    
    NSLog(@"%@",self.arrs);
    NSLog(@"%@",self.imageArray);
    self.backgroundViews=[[UIView alloc] init];
    self.backgroundViews.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:self.backgroundViews];
    [self.backgroundViews mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.view.mas_top).offset(kNavbarHeight);
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
        make.height.equalTo(@(KmainScreenHeiht - kNavbarHeight - kBottomSafeHeight));
    }];
    
    
    
    //1.初始化layout
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    
    //2.初始化collectionView
    mainCollectionView=[[UICollectionView alloc] initWithFrame:CGRectMake(0, 15, self.view.frame.size.width, 250) collectionViewLayout:layout];
    [self.backgroundViews addSubview:mainCollectionView];
    mainCollectionView.backgroundColor = [UIColor clearColor];
    
    //3.注册collectionViewCell
    
    [mainCollectionView registerNib:[UINib nibWithNibName:NSStringFromClass([MyCusCollectionViewCell class]) bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"collectionCell"];
    
    //4.设置代理
    mainCollectionView.delegate = self;
    mainCollectionView.dataSource = self;
    
    
    //确定按钮
    self.BottomView =[[UIImageView alloc] init];
    self.BottomView.image=[UIImage imageNamed:@"icon_anniu_c"];
    self.BottomView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(GoConfig:)];
    tap.delegate=self;
    [self.BottomView addGestureRecognizer:tap];
    [self.backgroundViews addSubview:self.BottomView];
    [self.BottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self->mainCollectionView.mas_bottom).offset(35);
        make.left.equalTo(self.backgroundViews.mas_left).offset(30);
        make.right.equalTo(self.backgroundViews.mas_right).offset(-30);
        
    }];
    
    UILabel *backLab=[[UILabel alloc] init];
    backLab.text = @"确认上传";
    backLab.userInteractionEnabled =YES;
    backLab.textColor = [UIColor whiteColor];
    backLab.textAlignment = NSTextAlignmentCenter;
    [self.BottomView addSubview:backLab];
    [backLab mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.BottomView.mas_top).offset(25);
        make.left.equalTo(self.BottomView.mas_left);
        make.right.equalTo(self.BottomView.mas_right);
        make.height.equalTo(@(30));
    }];
    
}
#pragma mark collectionView代理方法

//每个section的item个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.imageArray.count+1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MyCusCollectionViewCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"collectionCell" forIndexPath:indexPath];
    if (indexPath.row==self.imageArray.count)
    {
        cell.iconImage.image=[UIImage imageNamed:@"icon_tjtp"];
        cell.deleBtn.hidden=YES;
    }else{
        
            cell.iconImage.image=self.imageArray[indexPath.row];

        
        cell.deleBtn.hidden=NO;
        cell.tag=123+indexPath.row;
    }
 
    cell.delegate=self;
    return cell;
}

//设置每个item的尺寸
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake((self.view.frame.size.width-46)/3, 110);
}


//设置每个item的UIEdgeInsets
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(10, 10, 10, 10);
}

//设置每个item水平间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 13;
}


//设置每个item垂直间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 10;
}

//点击item方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSLog(@"%ld",indexPath.row);
    
    if (indexPath.row==self.imageArray.count)
    {
        if (indexPath.row+1==6)
        {
            
        }else{
            UIAlertController *alert = [[UIAlertController alloc]init];
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
            UIAlertAction *deleteAction = [UIAlertAction actionWithTitle:@"本地" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self acquireLocal];
            }];
            UIAlertAction *archiveAction = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self acquireAlbum];
            }];
            [alert addAction:cancelAction];
            [alert addAction:deleteAction];
            [alert addAction:archiveAction];
            [self presentViewController:alert animated:YES completion:nil];
            
        }
    }
    
}
//删除图片
-(void)backName:(MyCusCollectionViewCell *)cells and:(UIButton *)btn{
    

    NSInteger idx = cells.tag-123;
    __weak typeof(self)weakSelf = self;

    dispatch_async(dispatch_get_main_queue(), ^{
        [weakSelf.imageArray removeObjectAtIndex:idx];
        [self->mainCollectionView reloadData];
    });
   

}

#pragma mark -获取本地图片
-(void)acquireLocal{
    LHGroupViewController *group = [[LHGroupViewController alloc]init];
    if (self.imageArray.count==0)
    {
        group.maxChooseNumber = 5;
    }else{
        
        group.maxChooseNumber = 5-self.imageArray.count;
        
    }
//    if (self.arrs.count==0)
//    {
//        self.imageArray=[NSMutableArray new];
//    }
    __weak AddPictureViewController *weakSelf = self;
    group.backImageArray = ^(NSMutableArray<PHAsset *> *array){
        __strong AddPictureViewController *strongSelf = weakSelf;
        if (array) {
            for (int i = 0; i<array.count; i++) {
                PHAsset *asset = array[i];
                [[LHPhotoList sharePhotoTool]requestImageForAsset:asset size:CGSizeMake(1080, 1920) resizeMode:PHImageRequestOptionsResizeModeFast completion:^(UIImage *image, NSDictionary *info) {
                    NSString *length  = [NSString stringWithFormat:@"%f*%f",image.size.width,image.size.height];
                    [self.localLength addObject:length];
                    [self.imageArray addObject:image];
                    //加载在页面中
                    [strongSelf setSpread];
                }];
            }
        }
    };
    [self presentViewController:[[UINavigationController alloc] initWithRootViewController:group] animated:YES completion:nil];
}
#pragma mark -获取相机相册
-(void)acquireAlbum{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
    {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.sourceType = sourceType;
        if ([[[UIDevice currentDevice].systemVersion componentsSeparatedByString:@"."].firstObject integerValue]  == 8) {
            self.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        }
        [self presentViewController:picker animated:YES completion:nil];
    }else
    {
        NSLog(@"模拟其中无法打开照相机,请在真机中使用");
    }
}
#pragma mark --
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(nonnull NSDictionary<NSString *,id> *)info {
    __block UIImage *originalImage = [info objectForKey:UIImagePickerControllerOriginalImage];
//    if (self.arrs.count==0)
//    {
//        self.imageArray=[NSMutableArray new];
//    }
    __weak AddPictureViewController *weakSelf = self;
    void(^imageBlock)() = ^(UIImage *image){
        __strong AddPictureViewController *strongSelf = weakSelf;
        if (!image) {
            image = [info objectForKey:UIImagePickerControllerOriginalImage];
        }
        NSString *length  = [NSString stringWithFormat:@"%f*%f",image.size.width,image.size.height];
        [strongSelf.localLength addObject:length];
        [strongSelf.imageArray addObject:image];
    };
    void(^dismissBlock)() = ^(){//声明
        __strong AddPictureViewController *strongSelf = weakSelf;
        [picker dismissViewControllerAnimated:YES completion:^{
            [strongSelf setSpread];
        }];
    };
    //写入本地
    [[LHPhotoList sharePhotoTool]saveImageToAblum:originalImage completion:^(BOOL success, PHAsset *asset) {
        if (success) {//存成功
            [[LHPhotoList sharePhotoTool]requestImageForAsset:asset size:CGSizeMake(1080, 1920) resizeMode:PHImageRequestOptionsResizeModeFast completion:^(UIImage *image, NSDictionary *info) {
                originalImage = [UIImage imageWithData:UIImageJPEGRepresentation(originalImage, 1) scale:originalImage.scale];
                imageBlock(originalImage);
                dismissBlock();
            }];
        }else{//存取失败
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                originalImage = [UIImage imageWithData:UIImageJPEGRepresentation(originalImage, 1) scale:originalImage.scale];
                imageBlock(originalImage);
                dispatch_sync(dispatch_get_main_queue(), ^{
                    dismissBlock();
                });
            });
        }
    }];
}
#pragma mark -展示UI在界面
-(void)setSpread{
    
    [mainCollectionView reloadData];
    
}
#pragma mark -上传
-(void)toUpload{
    for (int i = 0; i<self.imageArray.count; i++) {
        NSData *data = UIImageJPEGRepresentation(self.imageArray[i], 0.5);
        NSString *string = self.localLength[i];
        NSLog(@"%@---%lu",string,(unsigned long)data.length);
        NSLog(@"%@",self.imageArray);
    }
}

-(void)deleteImage:(UIButton *)btn{
    UIView *view  = btn.superview;
    NSInteger idx = [_scrollSubViews indexOfObject:view];
    [_scrollSubViews removeObject:view];
    [_imageArray removeObjectAtIndex:idx];
    [_localLength removeObjectAtIndex:idx];
    [_scrollSubFrame removeLastObject];
    [UIView animateWithDuration:0.2 animations:^{
        view.alpha = 0;
    } completion:^(BOOL finished) {
        [view removeFromSuperview];
        self.scrolView.contentSize = CGSizeMake(imageWidth*self.scrollSubViews.count, imageWidth);
        [UIView animateWithDuration:0.2 animations:^{
            for (NSInteger i = idx; i < self.scrollSubViews.count; i++) {
                UIView *item = self.scrollSubViews[i];
                item.frame = [(NSValue*)(self.scrollSubFrame[i]) CGRectValue];
            }
        } completion:^(BOOL finished) {
            if (finished) {
                //完成之后处理的code
                if (self.imageArray.count>0)
                {
                    self.merchantlab.hidden=YES;
                }else{
                    
                    self.merchantlab.hidden=NO;
                }
            }
        }];
    }];
}
#pragma mark --
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

//确认上传的点击事件
-(void)GoConfig:(UIGestureRecognizer *)tp{
    
    if (self.imageArray.count==0)
    {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"请选择要上传的图片" preferredStyle:UIAlertControllerStyleAlert];
        //创建添加按钮（可以写事件，也可以不写），可以创建多个按钮
        UIAlertAction *OKbtn = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        }];
        //添加按钮到alertVC上，并模态出来
        [alertVC addAction:OKbtn];
        [self presentViewController:alertVC animated:YES completion:nil];
        
        
    }else{//上传
        
        //暂时先把图片传到上一个页面(后期设置要上传成功以后发送通知)
       [[NSNotificationCenter defaultCenter]postNotificationName:@"addPT" object:nil userInfo:@{@"addPicture":self.imageArray}];
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
